<?php
// 替换为你申请的接口密钥
$apiKey = '20170328000043667';
$password='Y_G5c5ykEaL4u_2NAi6J';
$salt=rand(1000000000,5000000000);
$to=$_REQUEST['to'];
$englishText=preg_replace_callback("/([A-Z])/",function($em){
    return " ".strtolower($em[1]);
},$_REQUEST['q']);
// 要翻译的英文文本

$sign=md5($apiKey.$englishText.$salt.$password);
$englishText=urlencode($englishText);
if($to==""||$to=="zh") {
    $url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" . $englishText . "&from=en&to=zh&appid=" . $apiKey . "&salt={$salt}&sign={$sign}";
}else{
    $url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" . $englishText . "&from=zh&to=en&appid=" . $apiKey . "&salt={$salt}&sign={$sign}";
}
// 发送 GET 请求并获取响应
$response = file_get_contents($url);

// 解析响应数据
$responseData = json_decode($response, true);

// 提取翻译后的中文文本
$chineseText = $responseData["trans_result"][0]["dst"];
if($to=="en"){
    $chineseText=preg_replace("/ |\s/","_",$chineseText);
}
// 输出翻译结果
echo $chineseText;